import CommonDrawer from '@/components/CommonDrawer';
import CommonTable from '@/components/CommonTable';
import { formatSeconds } from '@/utils/format';
import request from '@/utils/request';
import { useRequest } from 'ahooks';
import dayjs from 'dayjs';
import { useEffect } from 'react';
import LineChart from '../LineChart';
import styles from './index.less';

const Detail = (props) => {
  const { open, record, onCancel } = props;
  const { data, runAsync } = useRequest(
    async (params) => {
      const res = await request({
        url: '/datas/summary/line/trip/group/daily/list',
        method: 'GET',
        params,
      });
      return res;
    },
    { manual: true },
  );

  useEffect(() => {
    if (open && record) {
      runAsync({
        lineId: record.lineId,
        fromTime: dayjs(record.fromTime).format('YYYY-MM-DD 00:00:00'),
        toTime: dayjs(record.toTime).format('YYYY-MM-DD 23:59:59'),
        index: 0,
        size: 0, // 设置较大的size以获取所有数据
      });
    }
  }, [open, record]);

  const columns = [
    {
      title: '序号',
      dataIndex: 'number',
      width: 65,
      render: (_, __, index) => index + 1,
    },
    {
      title: '线路',
      dataIndex: 'lineName',
      width: 280,
      render: () => record?.lineName || '-',
    },
    {
      title: '日期',
      dataIndex: 'day',
      width: 110,
      render: (day) => dayjs(day).format('YYYY-MM-DD'),
    },
    {
      title: '趟次数',
      dataIndex: 'total',
      width: 70,
    },
    {
      title: '平均时长',
      dataIndex: 'avgDuration',
      width: 110,
      render: (text) => formatSeconds(text),
    },
    {
      title: '平均装车时长',
      dataIndex: 'avgLoadDurations',
      width: 110,
      render: (text) => formatSeconds(text),
    },
    {
      title: '平均卸车时长',
      dataIndex: 'avgUnloadDurations',
      width: 110,
      render: (text) => formatSeconds(text),
    },
    {
      title: '总时长',
      dataIndex: 'duration',
      width: 100,
      render: (text) => formatSeconds(text),
    },
    {
      title: '总装车时长',
      dataIndex: 'loadDurations',
      width: 110,
      render: (text) => formatSeconds(text),
    },
    {
      title: '总卸车时长',
      dataIndex: 'unloadDurations',
      width: 110,
      render: (text) => formatSeconds(text),
    },
  ];

  return (
    <CommonDrawer
      title="详情"
      open={open}
      onClose={onCancel}
      width={1200}
      destroyOnHidden
      footer={null}
    >
      <div className={styles.detail}>
        <div className={styles.chart}>
          <LineChart open={open} data={data} />
        </div>
        <div className={styles.table}>
          <CommonTable columns={columns} dataSource={data} pagination={false} />
        </div>
      </div>
    </CommonDrawer>
  );
};

export default Detail;
